/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.mes.base.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.AllArgsConstructor;
import org.springblade.modules.mes.base.utils.StringUtils;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.node.ForestNodeMerger;
import org.springblade.core.tool.utils.CollectionUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.modules.mes.base.entity.DictTreeNode;
import org.springblade.modules.mes.base.entity.MaterialInfo;
import org.springblade.modules.mes.base.mapper.MaterialInfoMapper;
import org.springblade.modules.mes.base.service.IMaterialInfoService;
import org.springblade.modules.mes.base.vo.MaterialInfoVO;
import org.springblade.modules.mes.base.wrapper.MaterialInfoWrapper;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;

/**
 * 材料信息（材料库） 服务实现类
 *
 * @author BladeX
 * @since 2020-09-14
 */
@Service
@AllArgsConstructor
public class MaterialInfoServiceImpl extends BaseServiceImpl<MaterialInfoMapper, MaterialInfo> implements IMaterialInfoService {

	MaterialInfoMapper materialInfoMapper;

	@Override
	public IPage<MaterialInfoVO> selectMaterialInfoPage(IPage<MaterialInfoVO> page, MaterialInfoVO materialInfo) {
		materialInfo.setMaterialFlags(Func.toStrList(materialInfo.getMaterialFlag()));
		materialInfo.setMaterialTypes(Func.toStrList(materialInfo.getMaterialType()));
		return page.setRecords(baseMapper.selectMaterialInfoPage(page, materialInfo));
	}

	@Override
	public List<MaterialInfoVO> selectMaterialInfoList(MaterialInfoVO materialInfo) {
		return baseMapper.selectMaterialInfoList(materialInfo);
	}

	@Override
	public List<MaterialInfoVO> selectRawMaterialList(MaterialInfoVO materialInfo) {
		return materialInfoMapper.selectRawMaterialList(materialInfo);
	}

	@Override
	public List<MaterialInfo> listWithDeleted(Date startTime, Date endTime) {
		return materialInfoMapper.listWithDeleted(startTime, endTime);
	}


    @Override
    public List<MaterialInfoVO> materialList(MaterialInfoVO materialInfo) {
        List<MaterialInfoVO> materialInfos = baseMapper.getMaterialList(materialInfo);
        return materialInfos;
    }

    /**
     * 获取产品/物料信息
     * @param materialInfo
     * @return
     */
    @Override
    public R getMaterialInfo(MaterialInfoVO materialInfo) {
        List<MaterialInfoVO> material = baseMapper.getMaterialInfo(materialInfo);
        if (CollectionUtil.isNotEmpty(material)){
            for (MaterialInfoVO vo:material){
                if (vo.getItemWeight()!=null && vo.getItemWeight()>0){
                    vo.setItemWeight(new BigDecimal(vo.getItemWeight()).divide(new BigDecimal("1000")).doubleValue());
                }
            }
        }
        return R.data(material);
    }

    @Override
    public R getMaterialInfoByQuality(MaterialInfoVO materialInfo) {
        List<MaterialInfoVO> material = baseMapper.getMaterialInfoByQuality(materialInfo);
        if (CollectionUtil.isNotEmpty(material)){
            for (MaterialInfoVO vo:material){
                if (vo.getItemWeight()>0){
                    vo.setItemWeight(new BigDecimal(vo.getItemWeight()).divide(new BigDecimal("1000")).doubleValue());
                }
            }
        }
        return R.data(material);
    }

    @Override
    public List<MaterialInfoVO> fisMaterialList(MaterialInfoVO materialInfo) {
        materialInfo.setMaterialFlags(Func.toStrList(materialInfo.getMaterialFlag()));
        return baseMapper.fisMaterialList(materialInfo);
    }

    @Override
	public IPage<MaterialInfoVO> getQuaMaterialInfoPage(IPage<MaterialInfoVO> page, MaterialInfoVO materialInfo) {
		return page.setRecords(baseMapper.getQuaMaterialInfoPage(page, materialInfo));
	}


    @Override
    public List<MaterialInfo> getMaterialInfos() {
        return baseMapper.getMaterialInfos(AuthUtil.getTenantId());
    }

    @Override
    public List<MaterialInfoVO> getMaterialLists(MaterialInfoVO materialInfo) {
        return baseMapper.getMaterialLists(materialInfo);
    }

    @Override
    public R importMaterialInfo(Map<String, Object> map) {
        ArrayList<String[]> data = (ArrayList<String[]>) map.get("data");
        List<MaterialInfo> infoList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(data)) {
            List<String> noList = baseMapper.selectMaterialNo(AuthUtil.getTenantId());
            List<String> nameList = baseMapper.selectMaterialName(AuthUtil.getTenantId());
            Iterator<String[]> iterator = data.iterator();
            while (iterator.hasNext()) {
                String[] obj = iterator.next();
                if (StringUtils.isEmpty(obj[0])){
                    throw new ServiceException("物料编码不能为空！");
                }
                if (StringUtils.isEmpty(obj[1])){
                    throw new ServiceException("物料名称不能为空！");
                }
                if (StringUtils.isEmpty(obj[2])){
                    throw new ServiceException("物料类别不能为空！");
                }
                if (StringUtils.isEmpty(obj[3])){
                    throw new ServiceException("物料类型不能为空！");
                }
                if (StringUtils.isEmpty(obj[4])){
                    throw new ServiceException("物料组编码不能为空！");
                }
                if (StringUtils.isEmpty(obj[5])){
                    throw new ServiceException("计量单位不能为空！");
                }
                if (noList.contains(obj[0])){
                    throw new ServiceException("物料编码："+obj[0]+"  已存在！");
                }
                if (nameList.contains(obj[1])){
                    throw new ServiceException("物料名称："+obj[1]+"  已存在！");
                }
                MaterialInfo info = new MaterialInfo();
                info.setProductStatus("4");
                info.setMaterialNo(obj[0]);
                info.setMaterialName(obj[1]);
                info.setMaterialFlag(obj[2].trim());
                info.setMaterialType(obj[3].trim());
                info.setMaterialGroupNo(obj[4].trim());
                info.setInnerDrawingNo(obj[6]);
                info.setSpecifications(obj[7]);
                info.setModel(obj[8]);
                info.setDeliverSpec(obj[9]);
                infoList.add(info);
            }
        } else {
            throw new ServiceException("导入的数据不能为空！");
        }
        return R.status(super.saveBatch(infoList));
    }

    @Override
    public void exportMaterialInfo(HttpServletRequest request, HttpServletResponse response, MaterialInfoVO materialInfo, String ids) {
        if (StringUtils.isNotEmpty(ids)){
            List<MaterialInfo> list = baseMapper.selectBatchIds(Func.toLongList(ids));
            List<MaterialInfoVO> voList = MaterialInfoWrapper.build().listVO(list);
            Map<String,Object>map = new HashMap<>();
            map.put("list",voList);
//            ExcelUtil.export(request,response,map,"材料信息导出模板","材料信息据信息",false);
        } else {
            materialInfo.setMaterialFlags(Func.toStrList(materialInfo.getMaterialFlag()));
            List<MaterialInfoVO> voList = baseMapper.selectMaterialInfoPage(null,materialInfo);
            Map<String,Object>map = new HashMap<>();
            map.put("list",voList);
//            ExcelUtil.export(request,response,map,"材料信息导出模板","材料信息据信息",false);
        }
    }

    @Override
    public List<MaterialInfo> materialListByIdList(List<Long> longList) {
        return baseMapper.materialListByIdList(longList);
    }

    @Override
    public void deriveMaterial(MaterialInfoVO materialInfo, String ids, HttpServletRequest request, HttpServletResponse response) {
        Query query=new Query();
        query.setCurrent(-1);
        query.setSize(-1);
        IPage<MaterialInfoVO> page =  Condition.getPage(query);
        if (StringUtil.isNotBlank(ids)){
            List<Long> idList = Func.toLongList(ids);
            materialInfo.setIdList(idList);
        }
        List<MaterialInfoVO> list = baseMapper.selectMaterialInfoPage(page,materialInfo);
//        deriveSave(list);
        //定义模板名称
        String tempName = "物料信息组成料";
        //定义导出文件名
        String fileName = "物料信息组成料";
        //定义导出数据
        Map<String,Object> map = new HashMap<>();
//        map.put("list",installAndReplace(list));
        if (CollectionUtil.isNotEmpty(list)){
//            ExcelUtil.export(request,response,map,tempName,fileName,false);
        }
    }

    @Override
    public List<MaterialInfo> materialListByNoList(List<String> materialNoList) {
        return baseMapper.materialListByNoList(materialNoList);
    }

    @Override
    public R<List<MaterialInfo>> getMaterialInfoByPatrol(MaterialInfoVO materialInfo) {
        return R.data(baseMapper.selectMaterialInfoByPatrol(materialInfo));
    }

	@Override
	public List<DictTreeNode> getTree(String code, String dictKey) {
		return ForestNodeMerger.merge(baseMapper.getTree(code, Func.toStrList(dictKey)));
	}
}
